package com.servlet.listener;

import com.servlet.bean.User;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.List;

/**
 * @Title: MySessionAttributeListener
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/26 15:28
 */
@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        ServletContext servletContext = session.getServletContext();
        // 将之前的用户取出来
        List<User> list = (List<User>)servletContext.getAttribute("online");
        // 获取到当前登录用户
        User user =(User) httpSessionBindingEvent.getValue();

        if(list.stream().noneMatch(u -> u.getId().equals(user.getId()))) {
            list.add(user);
            servletContext.setAttribute("online",list);
        }


    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        ServletContext servletContext = session.getServletContext();
        // 将之前的用户取出来
        List<User> list = (List<User>)servletContext.getAttribute("online");
        // 获取到当前登录用户
        User user =(User) session.getAttribute("user");

        if(list.stream().noneMatch(u -> u.getId().equals(user.getId()))) {
            list.add(user);
            servletContext.setAttribute("online",list);
        }
    }
}
